package com.example.demo.controllers;

import com.example.demo.core.storage.RuleStorageMysql;
import com.example.demo.dal.model.TbRule;
import com.example.demo.core.entity.Greeting;
import com.example.demo.core.entity.Result;
import com.example.demo.core.RuleFlow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zuitu@foxmail.com
 * @date 2020/06/18
 */
@RestController
public class RuleController {
    @Autowired
    private RuleStorageMysql ruleStorage;
    @Autowired
    private RuleFlow ruleFlow;

    private static final String template = "welcome to, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/")
    public Greeting index(@RequestParam(value = "name", defaultValue = "fast NSM") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }

    @GetMapping("/result_list")
    public Result getResultList(@RequestBody Map<String, String> facts) {
        List<TbRule> ruleList = ruleStorage.getRuleList();
        return ruleFlow.getResult(facts, ruleList);
    }

    @PostMapping("/add_result")
    public Long addConclusion(@RequestParam(value = "name") String name, @RequestParam(value = "val") String val) {
        return ruleStorage.addRoot(name, val);
    }

    @PostMapping("/add_rule")
    public Long addRule(@RequestParam(value = "pid") Long pid, @RequestParam(value = "name") String name, @RequestParam(value = "val") String val, @RequestParam(value = "op") String op) {
        return ruleStorage.addChild(pid, name, val, op);
    }
}
